package com.example.flutterprinterapp;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;

public class MainActivity extends FlutterActivity {
    private static final String METHOD_CHANNEL = "com.mx.print/method_channel";
    private MethodChannel methodChannel;
    private static final String GET_SCANDATA = "nlscan.action.SCANNER_RESULT";
    private static final String SCAN_DATA = "SCAN_BARCODE1";
    public static final int UPDATE_LIST = 0x1000;
    private static final String DEVICE_SCAN = "device_scan";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        android.content.IntentFilter filter = new android.content.IntentFilter();
        filter.addAction(GET_SCANDATA);
        registerReceiver(mScanResultReceiver, filter);
    }


    @Override
    public void configureFlutterEngine(FlutterEngine flutterEngine) {
        super.configureFlutterEngine(flutterEngine);
        methodChannel = new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), METHOD_CHANNEL);
    }

    /**
     * 注册实体
     */
    private android.content.BroadcastReceiver mScanResultReceiver = new android.content.BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Toast.makeText(MainActivity.this, "toast", Toast.LENGTH_SHORT).show();
            if (action.equals(GET_SCANDATA)) {
                Bundle bundle = intent.getExtras();
                final String barcode = bundle.getString(SCAN_DATA);
                Message msg = mHandle.obtainMessage(UPDATE_LIST, barcode);
                mHandle.sendMessage(msg);
            }
        }
    };

    @SuppressLint("HandlerLeak")
    protected Handler mHandle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_LIST:
                    methodChannel.invokeMethod(DEVICE_SCAN, msg.obj);
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        unregisterReceiver(mScanResultReceiver);
        super.onDestroy();
    }
}
